package com.jt.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.*;
import redis.clients.jedis.*;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * redis配置类
 * @author dc
 * @Classname RedisConfig
 * @Date 2020/2/18 9:16
 */
@Configuration
@PropertySource("classpath:/properties/redis.properties")
public class RedisConfig {

    @Value("${redis.node}")
    private String redisNode;

    @Value("${redis.shards}")
    private String redisNodes;

    @Value("${redis.sentinel}")
    private String redisSentinel;

    @Value("${redis.cluster}")
    private String redisCluster;


    /**
     * 配置redis集群bean
     * @return
     */
    @Bean
    @Scope("prototype")
    public JedisCluster jedisCluster(){
        Set<HostAndPort> nodes = new HashSet<>();
        String[] setNodes = redisCluster.split(",");
        for(String node:setNodes){
            String host = node.split(":")[0];
            int port = Integer.parseInt(node.split(":")[1]);
            nodes.add(new HostAndPort(host,port));
        }
        return  new JedisCluster(nodes);
    }



    /**
     * 创建redis单主机连接
     * @return Jedis对象(单台主机)
     */
    //@Bean
    @Scope("prototype")
    public Jedis jedis(){
        String[] node = redisNode.split(":");
        String host=node[0];
        int port=Integer.parseInt(node[1]);
        return new Jedis(host,port);
    }

    /**
     * 配置redis分片机制
     * @return ShardJedis对象
     */
    //@Bean
    @Scope("prototype")
    public ShardedJedis shardedJedis(){
        List<JedisShardInfo> shards = new ArrayList<>();
        String[] nodes = redisNodes.split(",");
        for(String node:nodes){
            String[] str = node.split(":");
            String host=str[0];
            int port = Integer.parseInt(str[1]);
            shards.add(new JedisShardInfo(host,port));
        }
        return new ShardedJedis(shards);
    }

    /**
     * 整合redis哨兵
     * @return JedisSentinelPool对象
     */
    //@Bean
    public JedisSentinelPool jedisSentinelPool(){
        Set<String> sentinel = new HashSet<>();
        sentinel.add(redisSentinel);
        return new JedisSentinelPool("mymaster",sentinel);
    }

    /**
     * 动态获取池中对象
     * 知识点说明:
     * 1.Spring @Bean注解工作时,如果发现方法中有参数列表,则会自动注入
     * 2.@Qualifier 利用name属性,实现参数的赋值
     */
    //@Bean
    @Scope("prototype")
    public Jedis sentinelJedis(JedisSentinelPool jedisSentinelPool){
        return  jedisSentinelPool.getResource();
    }

}
